package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.dtos.RegisterDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.UUID;

@Service
@Slf4j
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * 用户登录
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //判断手机号和密码不为空
        if (!StringUtils.isBlank(loginDto.getPhone()) && !StringUtils.isBlank(loginDto.getPassword())){
            //根据手机号查询用户
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone,loginDto.getPhone());
            ApUser user = getOne(queryWrapper);
            //用户为空,抛出异常
            if (user==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"用户不存在");
            }
            //用户存在,则比较密码
            String salt = user.getSalt();
            String password = loginDto.getPassword();
            //通过md5 用户名加盐的方式还原密码
            String pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            //与用户密码进行比对
            if (!user.getPassword().equals(pwd)){
                //密码不正确,抛出异常
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }
            //密码正确,返回数据,通过jwt
            HashMap<String,Object> map = new HashMap<>();
            //存入token令牌
            map.put("token", AppJwtUtil.getToken(Long.valueOf(user.getId())));
            //存入用户数据,将密码和salt变为空
            user.setSalt("");
            user.setPassword("");
            map.put("user",user);
            return ResponseResult.okResult(map);
        }else {
            //如果是游客
            HashMap<String,Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        }
    }

    /**
     * 注册
     *
     * @param registerDto
     * @return
     */
    @Override
    public ResponseResult register(RegisterDto registerDto) {
        //首先查询手机号在数据库是否存在
        ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, registerDto.getPhone()));
        if (apUser!=null){
            //用户存在,抛出异常
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"用户已存在");
        }
        //判断两次密码是否一致
        if (!registerDto.getPwd().equals(registerDto.getPwd2())){
            //如果两次密码不一致则抛出异常
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"两次密码不一致");
        }
        //用户不存在则进行添加
        ApUser newUser = new ApUser();
        newUser.setPhone(registerDto.getPhone());
        //生成随机盐,uuid
        String uuid = UUID.randomUUID().toString();
        //截取-保留字符
        String salt = uuid.replace("-", "");
        log.info(salt);
        //随即盐+密码组合
        String pwd = DigestUtils.md5DigestAsHex((registerDto.getPwd() + salt).getBytes());
        newUser.setPassword(pwd);
        newUser.setSalt(salt);
        //保存数据库
        save(newUser);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
